package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Override
    public boolean isAsync() {
        return true;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context1) {
        CreateOrderContext context=(CreateOrderContext)context1;
        System.out.println("扣减库存处理器 context = " + context);

        String orderId = context.getOrderId();

        List<Long> ids = context.getBuyProductIds();
        System.out.println("SubStockHandler:ids = " + ids);
        List<CartProductDto> cartProductDtoList = context.getCartProductDtoList();
        if (CollectionUtils.isEmpty(ids)) {
            ids=new ArrayList<>();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                ids.add(cartProductDto.getProductId());
            }
//            ids=cartProductDtoList.stream().map(u -> u.getProductId())
//                    .collect(Collectors.toList());
        }
        ids.sort(Long::compareTo);
        System.out.println("sort ids = " + ids);

//        for (Long id : ids) {
//            Example example1=new Example(OrderItem.class);
//            example1.createCriteria()
//                    .andEqualTo("itemId",id);
//            List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
//            Integer num = orderItems.get(0).getNum();

        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(ids);
        if (CollectionUtils.isEmpty(stocksForUpdate)) {
            System.out.println(" \"stock has  not been inited!\" " );
            throw new BaseBusinessException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }
        if (ids.size() != stocksForUpdate.size()) {
            System.out.println("part of stock has  not been inited!");
            throw new BaseBusinessException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }
        for (CartProductDto productDto : cartProductDtoList) {
            Long productId = productDto.getProductId();
            Long productNum = productDto.getProductNum();
//            productNum between
//            Stock stock = new Stock();


            Example example = new Example(Stock.class);
            example.createCriteria()
                    .andEqualTo("itemId", productId);
            List<Stock> stocks = stockMapper.selectByExample(example);
            Stock stock = stocks.get(0);

            Integer restrictCount = stock.getRestrictCount();
            if (restrictCount >= productNum) {
                stock.setItemId(productId);
//            stock.setLockCount(Math.toIntExact(productNum));
                stock.setLockCount(productNum.intValue());
                stock.setStockCount(-productNum);
                stockMapper.updateStock(stock);

            } else {
                throw new BaseBusinessException("out of restrictCount of stock !");
            }
        }
//            stock.setLockCount(num);
//            stock.setStockCount(stock.getStockCount() - num);
//            stockMapper.updateByPrimaryKeySelective(stock);
//        }
        return true;
    }
}